import axios from 'axios';
import type { AxiosResponse, AxiosError } from 'axios';
import { ElMessage } from 'element-plus';
import router from '@/router';
import { filterParams } from '@/utils/utils';

// 设置开发环境和测试环境的前缀
const devUrl = '';
const formalUrl = '';
// development  /  production
// export const baseURL = process.env.NODE_ENV == 'development' ? devUrl : formalUrl;

const request = axios.create({
  timeout: 10000
  // baseURL: 'http://127.0.0.1:4523'
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    // 添加请求头等前置处理
    config.headers.Authorization = token;

    return config;
  },
  (error) => {
    // 请求错误处理
    console.log('Request Error:', error);
    return error;
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    // 响应后处理
    if (response.status === 200 && response.data.code === 200) {
      console.log('成功');
    } else {
      if (response.data.code) {
        switch (response.data.code) {
          case 401:
            // ElMessage.error('登陆失效，请重新登陆');
            router.push('/login');
            break;
          default:
            ElMessage.error(response.data.msg);
        }
      }
    }
    return response;
  },
  (error: AxiosError) => {
    return error;
  }
);

// get 请求封装
export const getRequest = async (url: string, params?: object, config?: object) => {
  const res: any = await request.get(url, { params: filterParams(params), ...config });
  // const res: any = await request.get(url, { params: params, ...config });
  return res.data;
};

// post 请求封装
export const postRequest = async (url: string, data?: object, config?: object) => {
  // const res: any = await request.post(url, filterParams(data));
  const res: any = await request.post(url, data, config);
  return res.data;
};

// put 请求封装
export const putRequest = async (url: string, data?: object) => {
  // const res: any = await request.put(url, filterParams(data));
  const res: any = await request.put(url, data);
  return res.data;
};

// delete 请求封装
export const deleteRequest = async (url: string, data?: object) => {
  // const res: any = await request.delete(url, { data: filterParams(data) });
  const res: any = await request.delete(url, { data });
  return res.data;
};

export default request;
